package com.ljk;

import com.ljk.util.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音操作工具类
 *
 * @author ljk
 * @date 2021/9/28 13:36
 * @since 1.0
 */
@Slf4j
public class PinYinUtil {

    public static void main(String[] args) {
        String hanzi = "肩关节手术工具（ACCU PASS 自动连续传递缝合钩）";

        String firstSpell = getFirstSpell(hanzi);
        System.out.println(firstSpell);
        String fullSpell = getFullSpell(hanzi);
        System.out.println(fullSpell);
    }

    /**
     * 获取汉字串拼音首字母，英文字符不变
     *
     * @param chinese 汉字串
     * @return 汉语拼音首字母
     */
    public static String getFirstSpell(String chinese) {
        if (StringUtil.isBlank(chinese)) {
            return chinese;
        }
        StringBuilder pybf = new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char c : arr) {
            if (c <= 128) {
                pybf.append(c);
                continue;
            }
            try {
                String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (temp != null && temp.length != 0) {
                    pybf.append(temp[0].charAt(0));
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        }
        return pybf.toString().replaceAll("\\W", "");
    }

    /**
     * 获取汉字串拼音，英文字符不变
     *
     * @param chinese 汉字串
     * @return 汉语拼音
     */
    public static String getFullSpell(String chinese) {
        if (StringUtil.isBlank(chinese)) {
            return chinese;
        }
        StringBuilder pybf = new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char c : arr) {
            if (c <= 128) {
                if (c != ' ') {
                    pybf.append(c);
                }
                continue;
            }
            try {
                String[] str = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (str != null && str.length != 0) {
                    pybf.append(str[0]);
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        }
        return pybf.toString();
    }

    /**
     * 汉字转拼音有音标,多音字全部返回
     *
     * @param hanZi 汉字
     * @return String 拼音
     * @author ljk
     * @date 2021/9/28 14:50
     */
    public static String[][] hanZiToPinyinArr(String hanZi) {
        // 输出格式设置
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        /*输出大小写设置; LOWERCASE:输出小写 UPPERCASE:输出大写*/
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        /*输出音标设置; WITH_TONE_MARK:直接用音标符（必须设置WITH_U_UNICODE，否则会抛出异常） WITH_TONE_NUMBER：1-4数字表示音标 WITHOUT_TONE：没有音标     */
        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
        /*特殊音标ü设置; WITH_V：用v表示ü WITH_U_AND_COLON：用"u:"表示ü WITH_U_UNICODE：直接用ü */
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        char[] hanYuArr = hanZi.trim().toCharArray();
        String[][] pinYin = new String[hanYuArr.length][];
        try {
            for (int i = 0, len = hanYuArr.length; i < len; i++) {
                // 匹配是否是汉字
                if (Character.toString(hanYuArr[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    // 如果是多音字，返回多个拼音
                    String[] pys = PinyinHelper.toHanyuPinyinStringArray(hanYuArr[i], format);
                    //          String[] pys = PinyinHelper.toGwoyeuRomatzyhStringArray(hanYuArr[i]);
                    pinYin[i] = pys;
                } else {
                    pinYin[i] = new String[0];
                }
            }
        } catch (Exception e) {
            log.error("转拼音报错:", e);
        }
        return pinYin;
    }
}
